package com.maori.languageapp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.maori.languageapp.R;
import com.maori.languageapp.adapter.Maori_NavDrawerListAdapter;
import com.maori.languageapp.consts.Maori_Glo_Pass;
import com.maori.languageapp.consts.UrlContant;
import com.maori.languageapp.curateword.Maori_Curate_Word;
import com.maori.languageapp.discover.Maori_Discover_Idiom;
import com.maori.languageapp.discover.Maori_Discover_Phrase;
import com.maori.languageapp.discover.Maori_Discover_Song;
import com.maori.languageapp.discover.Maori_Discover_Story;
import com.maori.languageapp.discover.Maori_Discover_Word;
import com.maori.languageapp.fragments.Maori_Main_Fragment;
import com.maori.languageapp.image.Maori_DownloadImage;
import com.maori.languageapp.model.Maori_NavDrawerItem;
import com.maori.languageapp.subview.Maori_BookMark_Items;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

public class Maori_Categories extends FragmentActivity {

	private String[] category_names;
	private String[] category_URL;
	private String[] category_noOfCount;
	private int[] category_MID;
	private int[] category_NCMID;
	private String[] category_count;

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;
	private ArrayList<Maori_NavDrawerItem> navDrawerItems;
	private Maori_NavDrawerListAdapter adapter;

	GridView gridView;
	int Capture_Type, Display_Type;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.maori_activity_categories);

		mTitle = mDrawerTitle = getTitle();

		navMenuTitles = getResources().getStringArray(
				R.array.maori_nav_drawer_items);

		navMenuIcons = getResources().obtainTypedArray(
				R.array.maori_nav_drawer_icons);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout_categories);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu_cat);

		navDrawerItems = new ArrayList<Maori_NavDrawerItem>();

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[0],
				navMenuIcons.getResourceId(0, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[1],
				navMenuIcons.getResourceId(1, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[2],
				navMenuIcons.getResourceId(2, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[3],
				navMenuIcons.getResourceId(3, -1), true, "22"));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[4],
				navMenuIcons.getResourceId(4, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[5],
				navMenuIcons.getResourceId(5, -1), true, "50+"));
		
		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[6], navMenuIcons
				.getResourceId(6, -1)));

		navMenuIcons.recycle();

		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		adapter = new Maori_NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		mDrawerList.setAdapter(adapter);

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setBackgroundDrawable(
				new ColorDrawable(Color.parseColor("#0d284c")));

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.menubutton, R.string.app_name, R.string.app_name) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		// PSJ
		/*
		 * if (savedInstanceState == null) { displayView(0); }
		 */

		// Display Option
		// Display_Types 1 Discover ***** Index : 100
		// Display_Types 2 Capture ***** Index : 200
		// Display_Types 3 Curate ***** Index : 300
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			Capture_Type = Integer.parseInt(extras.getString("Capture_Type"));
			Display_Type = Integer.parseInt(extras.getString("Display_Type"));
			Maori_Category_Service sa = new Maori_Category_Service(this);
			// sa.execute(new String[] {UrlContant.CategoryURL});
			sa.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
					new String[] { UrlContant.CategoryURL });

		}

	}

	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			gridView.setVisibility(View.GONE);
			displayView(position);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);

		MenuItem searchItem = menu.findItem(R.id.search);
		SearchView searchView = (SearchView) MenuItemCompat
				.getActionView(searchItem);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		switch (item.getItemId()) {
		case R.id.action_settings:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	private void displayView(int position) {
		Fragment fragment = null;
		switch (position) {
		case 0:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 1:
			fragment = new Maori_Main_Fragment(1);
			break;
		case 2:
			fragment = new Maori_Main_Fragment(2);
			break;
		case 3:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 4:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 5:
			//fragment = new Maori_Main_Fragment(0);
			Intent myIntent = new Intent(Maori_Categories.this,
					Maori_BookMark_Items.class);
			myIntent.putExtra("CATEGORY","word");
			myIntent.putExtra("BMNID","100");
			startActivity(myIntent);
			break;

		default:
			break;
		}

		if (fragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container_cat, fragment).commit();

			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			Log.e("MainActivity", "Error in creating fragment");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	// Web Service class that is used to get the data for categories
	public class Maori_Category_Service extends AsyncTask<String, Void, String> {

		protected final String TAG = null;
		private ProgressDialog progdialod;
		private Activity activity;
		private Context context;

		private int timeoutConnection = 5000;
		private int timeoutSocket = 45000;

		private byte[] buff = new byte[1024];
		private String retval = "";

		public Maori_Category_Service(Activity activity) {
			super();
			this.activity = activity;
			this.context = this.activity.getApplicationContext();

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progdialod = ProgressDialog.show(this.activity, "Search",
					"Updating", true, false);
		}

		@Override
		protected String doInBackground(String... urls) {

			HttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters,
					timeoutConnection);
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

			HttpClient client = new DefaultHttpClient(httpParameters);
			HttpGet request = new HttpGet(urls[0]);

			try {
				HttpResponse responce = client.execute(request);
				StatusLine status = responce.getStatusLine();

				HttpEntity entity = responce.getEntity();
				InputStream ist = entity.getContent();

				ByteArrayOutputStream content = new ByteArrayOutputStream();

				int readcount = 0;

				while ((readcount = ist.read(buff)) != -1) {

					content.write(buff, 0, readcount);
				}

				retval = new String(content.toByteArray());

				return retval;

			} catch (ClientProtocolException e) {
				e.printStackTrace();
				return new String();
			} catch (IOException e) {
				e.printStackTrace();
				return new String();
			}

		}

		@Override
		protected void onPostExecute(String result) {
			progdialod.dismiss();

			// ArrayList<Maori_Category> mapData = new
			// ArrayList<Maori_Category>();

			try {

				JSONArray appLink = new JSONArray(result);

				category_NCMID = new int[appLink.length()];
				category_MID = new int[appLink.length()];
				category_names = new String[appLink.length()];
				category_URL = new String[appLink.length()];
				category_count = new String[appLink.length()];
				category_noOfCount = new String[appLink.length()];
				
				for (int i = 0; i < appLink.length(); i++) {
					JSONObject category = appLink.getJSONObject(i);
					category_NCMID[i] = Integer.parseInt(category
							.getString("NCMID"));
					category_MID[i] = Integer.parseInt(category
							.getString("MID"));
					category_names[i] = category.getString("node_category");
					category_URL[i] = UrlContant.ImageURLConst
							+ category.getString("M_Source");
					category_noOfCount[i] = category.getString("CatTotals");
				}

			} catch (JSONException e) {
				Log.e("JSON Exeption", e.toString());
			}

			if (category_names != null) {

				gridView = (GridView) findViewById(R.id.gridView_categories);

				gridView.setAdapter(new ImgViewBaseAdap(this.activity));

				gridView.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent, View v,
							int position, long id) {

						// Capture_Type
						// 1-Maori_Capture_Word
						// 2-Maori_Capture_Phrase
						// 3-Maori_Capture_Story
						// 4-Maori_Capture_Song
						// 5-Maori_Capture_Idiom

						if (Capture_Type == 1 && Display_Type == 200) {

							Intent i = new Intent(getApplicationContext(),
									LanguageAppCaptureActivity.class);
							i.putExtra("NCMID", category_NCMID[position]);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Word");
							startActivity(i);

						} else if (Capture_Type == 2 && Display_Type == 200) {

							Intent i = new Intent(getApplicationContext(),
									LanguageAppCaptureActivity.class);
							i.putExtra("NCMID", category_NCMID[position]);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Phrase");
							startActivity(i);

						} else if (Capture_Type == 3 && Display_Type == 200) {

							Intent i = new Intent(getApplicationContext(),
									LanguageAppCaptureActivity.class);
							i.putExtra("NCMID", category_NCMID[position]);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Story");
							startActivity(i);

						} else if (Capture_Type == 4 && Display_Type == 200) {

							Intent i = new Intent(getApplicationContext(),
									LanguageAppCaptureActivity.class);
							i.putExtra("NCMID", category_NCMID[position]);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Song");
							startActivity(i);

						} else if (Capture_Type == 5 && Display_Type == 200) {

							Intent i = new Intent(getApplicationContext(),
									LanguageAppCaptureActivity.class);
							i.putExtra("NCMID", category_NCMID[position]);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Idiom");
							startActivity(i);

						}

						// Discover Navigation Pannel
						else if (Capture_Type == 1 && Display_Type == 100) {

							Intent i = new Intent(getApplicationContext(),
									Maori_Discover_Word.class);
							
							String NCMIDStr = Integer.toString(category_NCMID[position]); 
							i.putExtra("NCMID", NCMIDStr);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Word");
							startActivity(i);
							
						} else if (Capture_Type == 2 && Display_Type == 100) {

							Intent i = new Intent(getApplicationContext(),
									Maori_Discover_Phrase.class);
							String NCMIDStr = Integer.toString(category_NCMID[position]); 
							i.putExtra("NCMID", NCMIDStr);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Phrase");
							startActivity(i);

						}

						else if (Capture_Type == 3 && Display_Type == 100) {

							Intent i = new Intent(getApplicationContext(),
									Maori_Discover_Story.class);
							String NCMIDStr = Integer.toString(category_NCMID[position]); 
							i.putExtra("NCMID", NCMIDStr);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Idiom");
							Log.v(TAG, "***** Maori_Discover_Idiom *****:" + NCMIDStr + "|" + category_names[position]);
							startActivity(i);

						}

						else if (Capture_Type == 4 && Display_Type == 100) {

							Intent i = new Intent(getApplicationContext(),
									Maori_Discover_Song.class);
							String NCMIDStr = Integer.toString(category_NCMID[position]); 
							i.putExtra("NCMID", NCMIDStr);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Idiom");
							Log.v(TAG, "***** Maori_Discover_Song *****:" + NCMIDStr + "|" + category_names[position]);
							startActivity(i);

						} else if (Capture_Type == 5 && Display_Type == 100) {

							Intent i = new Intent(getApplicationContext(),
									Maori_Discover_Idiom.class);
							String NCMIDStr = Integer.toString(category_NCMID[position]); 
							i.putExtra("NCMID", NCMIDStr);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Idiom");
							Log.v(TAG, "***** Maori_Discover_Idiom *****:" + NCMIDStr + "|" + category_names[position]);
							startActivity(i);
						}
						
						//Curate
						
						else if (Capture_Type == 1 && Display_Type == 300) {

							Intent i = new Intent(getApplicationContext(),
									Maori_Curate_Word.class);
							
							String NCMIDStr = Integer.toString(category_NCMID[position]); 
							i.putExtra("NCMID", NCMIDStr);
							i.putExtra("node_category",
									category_names[position]);
							i.putExtra("type", "Word");
							startActivity(i);
							
						}
					}
				});

			}

		}
	}

	// Adapter Class That is used for the category grid view
	class ImgViewBaseAdap extends BaseAdapter {

		private Context context;
		LayoutInflater inflater;

		public ImgViewBaseAdap(Context context) {
			this.context = context;
			this.inflater = LayoutInflater.from(context);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;

			if (convertView == null) {
				convertView = inflater.inflate(
						R.layout.maori_gridview_item_layout, null);
				holder = new ViewHolder();
				holder.textView = (TextView) convertView
						.findViewById(R.id.titlegirditem);
				holder.noOfCount = (TextView) convertView
						.findViewById(R.id.noOfCount);
				holder.imageVw = (ImageView) convertView
						.findViewById(R.id.imggriditem);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			String noshw = category_URL[position];
			holder.textView.setText(category_names[position]);
			holder.noOfCount.setText(category_noOfCount[position]);

			if (Maori_Glo_Pass.imageAvailable(noshw)) {
				Bitmap imgvw = Maori_Glo_Pass.getImage(noshw);
				// holder.imageVw.setImageBitmap(imgvw);
				holder.imageVw.setImageBitmap(getRoundedCornerBitmap(imgvw));

			} else {
				// new Maori_DownloadImage(holder.imageVw).execute(noshw);
				new Maori_DownloadImage(holder.imageVw).executeOnExecutor(
						AsyncTask.THREAD_POOL_EXECUTOR, noshw);
			}
			// this.notifyDataSetChanged();

			/* convertView.measure(100, 100); */

			return convertView;
		}

		@Override
		public int getCount() {
			return category_names.length;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

	}

	// View Holder That is used to hold Category Imageview and Text
	public static class ViewHolder {
		public TextView textView;
		public ImageView imageVw;
		public TextView noOfCount;
	}

	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = 12;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}
	public void onBackPressed() {
		super.onBackPressed();
		displayCancelDialog();
	}

	protected void displayCancelDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Maori_Categories.this);
		builder.setTitle("CANCEL");
		builder.setMessage("Are Sure You Want To Exit...");
		builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Intent myIntent = new Intent(getBaseContext(),
						Maori_UserLoginActivity.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});
		builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
			}
		});
		builder.show();
	}
	
	//***********Memory Handling****************
	@Override
	   protected void onStop(){
	      super.onStop();
	   }

	   //Fires after the OnStop() state
	   @Override
	   protected void onDestroy() {
	      super.onDestroy();
	      try {
	         trimCache(this);
	      } catch (Exception e) {
	         // TODO Auto-generated catch block
	         e.printStackTrace();
	      }
	   }

	   public static void trimCache(Context context) {
	      try {
	         File dir = context.getCacheDir();
	         if (dir != null && dir.isDirectory()) {
	            deleteDir(dir);
	         }
	      } catch (Exception e) {
	         // TODO: handle exception
	      }
	   }

	   public static boolean deleteDir(File dir) {
	      if (dir != null && dir.isDirectory()) {
	         String[] children = dir.list();
	         for (int i = 0; i < children.length; i++) {
	            boolean success = deleteDir(new File(dir, children[i]));
	            if (!success) {
	               return false;
	            }
	         }
	      }

	      // The directory is now empty so delete it
	      return dir.delete();
	   }
}
